/*
 *    Document   : Cursos
 *    Created on : 01/04/2013, 11:07:15
 *    Author     : Fiúza <rbfiuza@gmail.com>
 */

Ext.define('FC.controller.CursoProjeto', {
    extend: 'Ext.app.Controller',

    stores:['CursoProjeto'],
    models:['CursoProjeto'],
    views:['CursosProjetoList','CursoList'],
   
   refs: [{
        ref: 'cursoList',
        selector: 'form'
    }],
   
   
    init : function() {
        this.control({
                    
            'viewport' : {
                render : this.onPanelRendered
            },
            'cursosProjetoList': {
                edit: this.editCurso,
                selectionchange: this.gridSelectionChange
                
            },
            'actionbuttoncolumn':{
                removeCurso : this.removeCurso
            },
            'cursoList': {
                edit: this.editCurso
                ,reload: this.reloadCursoProjetoList
                ,create: this.createCurso
            }
            
        });
    },
 
 
    createCurso: function(element,values){
        Ext.Ajax.request({
            url: 'criaCursoProjeto',
            params: {
                recordInfo: Ext.encode(values)
            },
            scope:this,
            //method to call when the request is successful
            success: this.onCreateSuccess,
            //method to call when the request is a failure
            failure: this.onCreateFailure
        });

    },
    onCreateFailure: function(){
        Ext.Msg.alert('Status','Falha ao Criar Curso Projeto');
    },
    onCreateSuccess: function(){
        Ext.Msg.alert('Status','Criado com Sucesso');

        var element = Ext.getCmp('cursosProjetoList');
                element.getStore().load({
                    params: {
                        idprojeto: FC.model.Global.idProjeto
                    }
                });

        var curso = Ext.getCmp('cursoprojetolist');
        curso.getForm().reset();
        
    },
    
    checado: function() {
        console.log('item');
    },
    
    reloadCursoProjetoList: function(element){

        var storeCursoProjeto = this.getCursoProjetoStore();
        storeCursoProjeto.load();

//        var storeCursoProjeto = this.getCursoProjetoStore();
//
//        storeCursoProjeto.load({
//            params: {
//                idprojeto: element.items.items[1].value
//            }
//        });

    },
 
    gridSelectionChange: function(model, records) {

          if (records[0]) {
               this.getCursoList().getForm().reset();
               this.getCursoList().getForm().loadRecord(records[0]);
               this.getCursoList().getForm().findField('qntPolos').setValue('0');

               var button = this.getCursoList().getForm().owner.query('button[text=Savar]');
               button[0].enable();

               for(cont = 0;cont < records[0].data.listPolos.length ; ++cont){
                    this.getCursoList().getForm().findField(''+records[0].data.listPolos[cont].polo).setValue(true);
               }
          }
      },

      onViewReady: function(grid) {
          grid.getSelectionModel().select(0);
      }, 
 
    onPanelRendered : function() {
        //just a console log to show when the panel is rendered
        Ext.MessageBox.alert('Status', 'Teste');
        
    },
            
    editCurso : function(editor, obj) {
        //check if record is dirty
        if(obj.record.dirty){
            //check if the record is valid   
//            console.log(obj.record.validate());
            if(obj.record.validate().isValid()){
                //Make your Ajax request to sync data
                mode = (obj.record.get('userId') === "") ? 'insert': 'update';
                this.syncData(obj, mode);
            }
        }
    },
            
            
    removeCurso : function(rowIndex) {
        
        Ext.Ajax.request({
            url: 'removeCurso',
            params: {
                store_id: 1
//                ,action: 'remove'
                ,rowIndex: rowIndex
                ,recordInfo: Ext.encode(this.getCursoProjetoStore().getAt(rowIndex).data)
            },
            scope:this,
            //method to call when the request is successful
            success: this,
            //method to call when the request is a failure
            failure: this
        });
        
    },
            
    //Sync data with the server 
    syncData : function(obj, mode) {
        Ext.Ajax.request({
            url: 'atualizaCursoProjeto',
            params: {
                store_id: 1,
                action: mode,
                rowIndex: obj.rowIdx,
                recordInfo: Ext.encode(this.getCursoProjetoStore().getAt(obj.rowIdx).data)
            },
            scope:this,
            //method to call when the request is successful
            success: this.onSaveSuccess,
            //method to call when the request is a failure
            failure: this.onSaveFailure
        });
    },

    onSaveFailure: function(err){
        //Alert the user about communication error
        Ext.MessageBox.alert('Status', 'Error occured during update CursoProjeto');
    },
    
    onSaveSuccess: function(response,opts){
        //Remove dirty
        var ajaxResponse = Ext.decode(response.responseText);
        if(ajaxResponse.success){
            //if we are doing an insert then get the new customerId 
            //and update the store record
            if(opts.params.action === 'insert'){
                cursoId = ajaxResponse.cursoId;
                this.getCursoProjetoStore().getAt(opts.params.rowIndex).set('customerId',cursoId);
            }

            this.getCursoProjetoStore().getAt(opts.params.rowIndex).set('id',ajaxResponse.cursoprojeto.id);
            this.getCursoProjetoStore().getAt(opts.params.rowIndex).set('idProjeto',ajaxResponse.cursoprojeto.idProjeto);            
            this.getCursoProjetoStore().getAt(opts.params.rowIndex).set('curso',ajaxResponse.cursoprojeto.curso);
            this.getCursoProjetoStore().getAt(opts.params.rowIndex).set('nivel',ajaxResponse.cursoprojeto.nivel);
            this.getCursoProjetoStore().getAt(opts.params.rowIndex).set('qntCursista',ajaxResponse.cursoprojeto.qntCursista);
            this.getCursoProjetoStore().getAt(opts.params.rowIndex).set('qntPolos',ajaxResponse.cursoprojeto.qntPolos);
            this.getCursoProjetoStore().getAt(opts.params.rowIndex).set('cargaHoraria',ajaxResponse.cursoprojeto.cargaHoraria);
            this.getCursoProjetoStore().getAt(opts.params.rowIndex).set('modulos',ajaxResponse.cursoprojeto.modulos);
            this.getCursoProjetoStore().getAt(opts.params.rowIndex).set('qntMeses',ajaxResponse.cursoprojeto.qntMeses);
            this.getCursoProjetoStore().getAt(opts.params.rowIndex).set('qntVagaTotal',ajaxResponse.cursoprojeto.qntVagaTotal);
            this.getCursoProjetoStore().getAt(opts.params.rowIndex).commit();
//            this.getDiariasStore().save();

        }
        else {
            Ext.MessageBox.alert('Status', 'Error occured during update CursoProjeto');
        }


//      e.record.set(e.field,gridValue);
//      e.record.commit();
//      myGrid.getView().refresh();
    

    
    }
});